package com.demo.datastructure.array;

/**
 * @author ljr
 * @version 1.0
 * @description: 稀疏数组的实现，这里采用五子棋, 默认为0, 黑子为1, 白子为2
 * @date 2021/10/1 17:36
 */
public class MySparseArray {

    public static int[][] buildSparseArray(int[][] args){
        int row = args.length;
        if(row == 0) throw new RuntimeException("");
        int cols = args[0].length;
        if(cols == 0) throw new RuntimeException("");
        int num = 0;
        for(int i = 0; i < row; i++){
            for(int l = 0; l < cols; l++){
                if(args[i][l] ==  0){ continue;}
                num++;
            }
        }

        if(num == 0) throw new RuntimeException("");

        int[][] sparseArray = new int[num+1][3];
        sparseArray[0][0] = row;
        sparseArray[0][1] = cols;
        sparseArray[0][2] = num;
        int rows = 1;
        for(int i = 0; i < row; i++){
            for(int l = 0; l < cols; l++){
                if(args[i][l] ==  0){ continue;}
                sparseArray[rows][0] = i;
                sparseArray[rows][1] = l;
                sparseArray[rows][2] = args[i][l];
                rows++;
            }
        }
        return sparseArray;
    }


    public static int[][] buildDyadicArray(int[][] sparseArray){
        int row = sparseArray.length;
        if(row == 0 || row == 1) throw new RuntimeException("");
        int rows = sparseArray[0][0];
        int clos = sparseArray[0][1];
        int[][] dyadicArray = new int[rows][clos];
        int num = 1;
        for(int i = 0; i < rows; i++){
            for(int l = 0; l < clos; l++){
                if(i != sparseArray[num][0] || l !=sparseArray[num][1]){
                    continue;
                }
                dyadicArray[i][l] = sparseArray[num][2];
                if(num++ == row-1){

                    break;
                }
            }
            if(num == row){
                break;
            }
        }
        return dyadicArray;
    }

    public static void main(String[] args) {
        int[][] ints = new int[11][11];
        ints[2][3] = 1;
        ints[3][4] = 2;
        int[][] sparseArray = MySparseArray.buildSparseArray(ints);
        int[][] dyadicArray = MySparseArray.buildDyadicArray(sparseArray);
        for(int[] row : dyadicArray){
            for(int data : row){
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
    }


}
